package com.bluefish.bltuan.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.bluefish.bltuan.cache.ApplicationUtils;
import com.bluefish.bltuan.service.CategoryService;
import com.bluefish.bltuan.service.ContentService;
import com.bluefish.bltuan.service.EmailTemplateService;

public class ApplicationListener implements ServletContextListener{

	public void contextDestroyed(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		ApplicationUtils.destroyMenus(context);
		ApplicationUtils.destroyTemplates(context);
		ApplicationUtils.destroyCMS(context);
	}

	public void contextInitialized(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		ApplicationContext applicationContext = (ApplicationContext) context.getAttribute(
				WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		
		CategoryService categoryService = getBean(applicationContext,"categoryService");
		ApplicationUtils.initCities(context, categoryService);
		
		EmailTemplateService emailTemplateService = getBean(applicationContext
				, "emailTemplateService");
		ApplicationUtils.initEmailTemplates(context, emailTemplateService);
	
		ContentService contentService = getBean(applicationContext, "contentService");
		ApplicationUtils.initCMS(context, contentService);
	}
	
	@SuppressWarnings("unchecked")
	private<T> T getBean(ApplicationContext context, String beanName){
		return (T) context.getBean(beanName);
	}

}
